﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
using System.Xml;
using System.Windows.Markup;
using System.IO;

namespace Zero.UControl.Base.Helper
{
    internal class XamlHelper
    {
        public void SaveCanvasElementsToFile(Canvas canvas, string filePath)
        {
            var elements = canvas.Children.OfType<UIElement>().ToList();

            // 创建临时容器来序列化
            var tempCanvas = new Canvas();
            foreach (var elem in elements)
            {
                tempCanvas.Children.Add(elem);
            }

            using var writer = XmlWriter.Create(filePath, new XmlWriterSettings
            {
                Indent = true
            });

            XamlWriter.Save(tempCanvas, writer);
        }

        public void LoadCanvasElementsFromFile(Canvas targetCanvas, string filePath)
        {
            if (!File.Exists(filePath)) return;

            using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            var loadedCanvas = XamlReader.Load(fs) as Canvas;

            if (loadedCanvas == null) return;

            targetCanvas.Children.Clear(); // 清除原有元素
            foreach (UIElement child in loadedCanvas.Children)
            {
                // 如果需要设置位置/交互/事件，这里可以重设
                targetCanvas.Children.Add(child);
            }
        }

    }
}
